package com.dinnerorders.core.services.impl;

import com.dinnerorders.common.services.DAO;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author Sergey Nalivko e-mail: snalivko93@gmail.com
 */
public abstract class BaseDAO <T> implements DAO<T> {

    @PersistenceContext(unitName = "dataPU")
    protected EntityManager entityManager;

    /**
     * @inheritDoc
     */
    @Override
    @Transactional
    public <T> T find(Class<T> entityClass, Object id) {
        return entityManager.find(entityClass, id);
    }

    /**
     * @inheritDoc
     */
    @Override
    @Transactional
    public <T> T update(T entity) {
        return entityManager.merge(entity);
    }

    /**
     * @inheritDoc
     */
    @Override
    @Transactional
    public void delete(T entity) {
        entityManager.remove(entity);
    }

    /**
     * @inheritDoc
     */
    @Override
    @Transactional
    public void save(T entity) {
        entityManager.persist(entity);
    }
}
